import { ShelfPackage } from '@/api/Shelf';
import { CategoryCascader } from '@/components/CategoryCascader';
import { CoursewaresList } from '@/components/CoursewaresList';
import { SourceSelectModal } from '@/components/SourceSelect';
import Source from '@/components/SourceSelect/Entity/Source';
import { useRequest } from 'ahooks';
import type { UploadFile } from 'antd';
import { Button, Card, Form, Input, message, Space } from 'antd';
import { useMemo, useState } from 'react';
import { useYmAliOss, YmAddPageLayout, YmUpload, type YmAddPageLayoutProps } from 'ym-design';
import { PackageInfo } from '../interface';

export interface AddEditPorps extends PackageInfo {
  onBack?(): void;
}

type FormValue = {
  coursewares: Source[];
  classId: string;
  packageName: string;
  faceImg?: UploadFile[];
};

const { PaneItem } = YmAddPageLayout;

export function AddEdit({ classId, parClassId, packageId, faceImg, packageName, onBack }: AddEditPorps) {
  const [itemProps] = CategoryCascader.useFieldLevelTwo(classId && parClassId ? [parClassId, classId] : undefined);
  const [form] = Form.useForm<FormValue>();
  const [modalOpen, setModalOpen] = useState<number>();

  useRequest(
    async () => {
      if (packageId) {
        return Source.listWithRelationType('package', packageId);
      }
    },
    {
      ready: Boolean(packageId),
      onSuccess(data) {
        form.setFieldsValue({ coursewares: data });
      },
    },
  );

  const { run, loading } = useRequest(ShelfPackage.create, {
    manual: true,
    onSuccess() {
      onBack?.();
    },
  });

  const customRequest = useYmAliOss();

  // 提交
  const formSub = async () => {
    const { coursewares: _coursewares, faceImg: _faceImg, ...value } = await form.validateFields();

    if (_coursewares.length === 0) {
      message.error('请选择学习内容');
      return;
    } else if (_coursewares.length > 20) {
      message.error('课件包最多添加20个课件');
      return;
    }
    const params = {
      ...value,
      packageId,
      coursewares: _coursewares.map((v, index) => {
        return {
          coursewareId: v.id,
          sortNum: index + 1,
        };
      }),
      faceImg: _faceImg?.map((v) => v.response ?? v.url).join(','),
    };
    run(params);
  };
  const operationFooter = useMemo(() => {
    const operationBtn = [
      <Button key="subOnce" type="primary" size="small" onClick={formSub} disabled={loading}>
        保存
      </Button>,
    ];
    return operationBtn;
  }, [loading]);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          onBack?.();
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );

  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem tabKey="tab1" label={packageId ? '编辑课件包' : '创建课件包'} className="pane_tab1">
        <div style={{ height: '100%', overflow: 'auto' }}>
          <Form
            form={form}
            labelCol={{ style: { width: 100 } }}
            initialValues={{
              classId,
              coursewares: [],
              faceImg: faceImg ? [{ url: faceImg, uid: faceImg }] : [],
              packageName,
            }}
          >
            <Card title="基础信息" style={{ marginBottom: 16 }}>
              <Form.Item label="课件包名称" name="packageName" rules={[{ required: true }]}>
                <Input showCount maxLength={18}></Input>
              </Form.Item>
              <Form.Item label="分类" name="classId" {...itemProps} rules={[{ required: true }]}>
                <CategoryCascader />
              </Form.Item>
              <Form.Item label="封面图">
                <Space size={20}>
                  <Form.Item name="faceImg" noStyle rules={YmUpload.formRules(false)}>
                    <YmUpload maxCount={1} cardWidth={375} cardHeight={200} customRequest={customRequest}>
                      请上传封面
                    </YmUpload>
                  </Form.Item>
                  <div>
                    <p>图片仅支持jpg、png格式 </p>
                    <p> 图片大小750*400 </p>
                  </div>
                </Space>
              </Form.Item>
            </Card>
            <Card
              title="选择课件"
              extra={
                <Button
                  type="primary"
                  shape="round"
                  onClick={() => {
                    setModalOpen(Math.random());
                  }}
                >
                  选择
                </Button>
              }
            >
              <Form.Item name="coursewares" noStyle>
                <SourceSelectModal openDep={modalOpen} preSet="课件"></SourceSelectModal>
              </Form.Item>
              <Form.Item name="coursewares" noStyle>
                <CoursewaresList />
              </Form.Item>
            </Card>
          </Form>
        </div>
      </PaneItem>
    </YmAddPageLayout>
  );
}
